package com.hymjweb.demo;

import com.hymjweb.demo.framework.util.DateUtil;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class PasswordUtil {




    private static String md5(String s){
        try {

            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes(StandardCharsets.UTF_8));

            return toHex(bytes);

        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes){
        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for(int i=0;i<bytes.length;i++){
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }


    private static String salt(){
        Random random=new Random();
        int rannum= (int)(random.nextDouble()*(99999-10000 + 1))+ 10000;
        String rand= DateUtil.dateToStr(new Date(),"yyyyMMdd") + rannum;
        return rand;
    }

    public static String encode(String password){
        String hexPwd = md5(password);
        System.out.println(hexPwd);
        String salt = salt();
        System.out.println(salt);
        StringBuilder builder = new StringBuilder(hexPwd);
        builder.insert(18,salt);
        //System.out.println(builder.toString());
        builder.replace(18,31,"");
        System.out.println(builder.toString());
        String pwd = md5(builder.toString());
        System.out.println(pwd);
        return pwd;
    }

    public static boolean match(String password,String dbPassword){
        StringBuilder builder = new StringBuilder(dbPassword);
        builder.replace(18,26,"");
        password = md5(password);
        return password.equals(builder.toString());
    }

    public static void main(String[] args) {

        String password = "cndsHFHknvildhnoiseygh/;'.''..";
        String encode = encode(password);
        System.out.println(encode);
        //System.out.println(match(password, encode));


    }


}
